
from flask import Flask, jsonify, request, send_file, make_response
import threading
import socket
import time
from queue import Queue
import logging
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("TCP Bridge")

# 线程共享数据存储
class ThreadSafeData:
    def __init__(self):
        self.lock = threading.Lock()
        self._data = None
        self.last_update = 0
        self.connection_status = False

    def update(self, new_data):
        with self.lock:
            self._data = new_data
            self.last_update = time.time()

    @property
    def data(self):
        with self.lock:
            return self._data

    @property
    def status(self):
        with self.lock:
            return self.connection_status

    def set_status(self, status):
        with self.lock:
            self.connection_status = status

# 全局状态存储
shared_data = ThreadSafeData()
command_queue = Queue()

class TCPClientThread(threading.Thread):
    def __init__(self, host, port):
        super().__init__(daemon=True)
        self.host = host
        self.port = port
        self.running = True
        self.reconnect_interval = 5  # 重连间隔(秒)
        self.buffer_size = 4096
        self.sock = None

    def run(self):
        while self.running:
            try:
                self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.sock.settimeout(1)
                self.sock.connect((self.host, self.port))
                shared_data.set_status(True)
                logger.info(f"Connected to {self.host}:{self.port}")

                # 开始接收数据
                while self.running:
                    try:
                        # 处理待发送命令
                        if not command_queue.empty():
                            cmd = command_queue.get()
                            self.sock.sendall(cmd.encode() + b'\r\n')
                            logger.debug(f"Sent command: {cmd}")

                        # 接收数据
                        data = self.sock.recv(self.buffer_size)
                        if data:
                            logger.info(f"receive tcp data: {data}")
                            shared_data.update(data.decode().strip())
                            self.sock.send(bytes("Hello world", "utf-8"))
                        else:
                            break  # 连接关闭

                    except socket.timeout:
                        continue  # 正常轮询超时
                    except Exception as e:
                        logger.error(f"Data error: {str(e)}")
                        break

            except Exception as e:
                logger.error(f"Connection error: {str(e)}")
                shared_data.set_status(False)
                
            finally:
                if self.sock:
                    self.sock.close()
                logger.info(f"Reconnecting in {self.reconnect_interval}s...")
                time.sleep(self.reconnect_interval)

    def stop(self):
        self.running = False
        if self.sock:
            self.sock.close()

import camera
class CameraThread(threading.Thread):
    img_path = None
    def __init__(self):
        super().__init__(daemon=True)
        self.logger = logger
        
    def run(self):
        camera.camera_executor(self)

    def stop(self):
        pass


# 初始化TCP线程
tcp_thread = TCPClientThread('192.168.11.254', 60000)
camera_thread = CameraThread()
tcp_thread.start()
camera_thread.start()

@app.route('/api/vehicle-data', methods=['GET'])
def get_data():
    if not shared_data.status:
        return jsonify({"error": "TCP connection down"}), 503
    
    data = shared_data.data
    if data:
        return jsonify({
            "data": data,
            "timestamp": shared_data.last_update
        })
    else:
        return jsonify({"error": "No data received yet"}), 404

@app.route('/api/command', methods=['POST'])
def send_command():
    # 这里添加命令验证逻辑
    command = request.json.get('command')
    if command:
        logger.info(f"command isssssssss {command}")
        command_queue.put(command)
        return jsonify({"status": "queued"})
    return jsonify({"error": "Invalid command"}), 400


# @app.route('/api/picture', methods=['GET'])
# def get_picture():
#     img_path = CameraThread.img_path
#     return send_file(img_path, mimetype='image/jpg')
@app.route('/api/picture', methods=['GET'])
def get_picture():
    try:
        import camera
        img_path_tmp = camera.camera_executor_1()
        print(f"img_path_tmp is {img_path_tmp}")
        # 添加缓存控制头
        response = make_response(send_file(
            img_path_tmp,
            mimetype='image/jpeg',  # 修正mime类型
            as_attachment=False
        ))
        
        # 设置缓存控制头
        response.headers['Cache-Control'] = 'no-store, max-age=0'
        response.headers['Pragma'] = 'no-cache'
        return response
    except Exception as e:
        print(f"图片发送失败: {str(e)}")
        return {'error': '图片未找到'}, 404
@app.route('/health')
def health_check():
    return jsonify({
        "tcp_connected": shared_data.status,
        "last_update": shared_data.last_update,
        "queue_size": command_queue.qsize()
    })

# 安全关闭处理
import atexit
@atexit.register
def cleanup():
    tcp_thread.stop()
    tcp_thread.join()
    logger.info("Service shutdown complete")

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=4999, threaded=True)